package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.service.*;
import com.zzyl.util.CodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-07
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private IElderService elderService;
    @Autowired
    private IBedService bedService;
    @Autowired
    private IContractService contractService;
    @Autowired
    private ICheckInConfigService checkInConfigService;
    @Autowired
    private ICheckInService checkInService;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto dto) {
        //校验老人是否入住
        Elder elder = elderService.lambdaQuery()
                .eq(Elder::getIdCardNo,dto.getCheckInElderDto().getIdCardNo())
//                .eq(Elder::getStatus,1)//1表示入住
                .one();
        if(elder != null && elder.getStatus() == 1){//老人注册完，并且已经入住则，不会需要新增老人也不需要修改老人任何信息
            throw new RuntimeException("该老人已入住");
        }
        //更新床位状态
        Bed bed = new Bed();
        bed.setBedStatus(1);
        bed.setId(dto.getCheckInConfigDto().getBedId());
        bedService.updateBed(bed);
        //根据bedid查询bed
        Bed dbBed = bedService.getById(dto.getCheckInConfigDto().getBedId());
        if(dbBed == null){
            throw new RuntimeException("床位没了");
        }
        //把前端的数据复制到新的elder对象中
        Elder newElder = BeanUtil.toBean(dto.getCheckInElderDto(), Elder.class);
        if(elder != null){
            newElder.setId(elder.getId());
        }
        newElder.setStatus(1);
        newElder.setBedId(dbBed.getId());
        newElder.setBedNumber(dbBed.getBedNumber());
        elderService.saveOrUpdate(newElder);//如果数据库有这个老人的数据则更新，没有的话则新增这个老人
        //签约合同，保存合同表
        Contract contract = BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contract.setElderName(newElder.getName());
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        contract.setElderId(newElder.getId());
        contract.setElderName(newElder.getName());
        //根据当前时间设置合同状态
        contract.setStatus(startDate.isBefore(LocalDateTime.now()) ? 1 : 0);
        contractService.save(contract);
        //入住配置信息
        CheckIn checkIn = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckIn.class);
        //把家属信息序列化成json字符串然后存到入住表remark字段里
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));
        checkIn.setElderName(newElder.getName());
        checkIn.setElderId(newElder.getId());
        checkIn.setIdCardNo(newElder.getIdCardNo());
        checkIn.setBedNumber(dbBed.getBedNumber());
        checkIn.setStatus(0);
        checkInService.save(checkIn);
        //新增入住配置
        CheckInConfig checkInConfig = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigService.save(checkInConfig);


//        Elder elder = elderService.lambdaQuery()
//                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
//                .one();
//        if(elder !=null && elder.getStatus()==1){
//            throw new RuntimeException("该老人已入住");
//        }//老人注册并且老人已经入住状态
        //更新床位状态
//        Bed bed = new Bed();
//        bed.setBedStatus(1);
//        bed.setId(dto.getCheckInConfigDto().getBedId());
//        bedService.updateBed(bed);
        //根据bedid查询bed
//        Bed dbBed = bedService.getById(dto.getCheckInConfigDto().getBedId());
//        if(dbBed==null){
//            throw new RuntimeException("床位没了");
//        }

//        Elder newElder = BeanUtil.toBean(dto.getCheckInElderDto(),Elder.class);
//        if(elder!=null){
//            newElder.setId(elder.getId());
//        }//这个判断是老人在养老院注册但是没有走完流程，还没入住的状态
//        newElder.setStatus(1);
//        newElder.setBedNumber(dbBed.getBedNumber());
//        newElder.setBedId(dbBed.getId());
//        elderService.saveOrUpdate(newElder);//如果这个对象的id在数据库里面有，更新，如果没有新增
        //新增签约办理
//        Contract contract = BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
//        contract.setElderId(newElder.getId());
//        contract.setElderName(newElder.getName());
//        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
//        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
//        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
//        contract.setStartDate(startDate);
//        contract.setEndDate(endDate);
//        //根据开始时间和当前时间对比
//        contract.setStatus(LocalDateTime.now().isAfter(startDate)?1:0);
//        contractService.save(contract);
//        //新增入住信息
//        CheckIn checkIn = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckIn.class);
//        checkIn.setElderName(newElder.getName());
//        checkIn.setElderId(newElder.getId());
//        checkIn.setIdCardNo(newElder.getIdCardNo());
//        checkIn.setBedNumber(dbBed.getBedNumber());
//        checkIn.setStatus(0);
//        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));//约定好把家属信息的json存到remark
//        this.save(checkIn);
//        //新增入住配置
//        CheckInConfig checkInConfig = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
//        checkInConfig.setCheckInId(checkIn.getId());
//        checkInConfigService.save(checkInConfig);

    }
}
